package de.ohmhochschule.bme;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;

public class AudioPlayerActivity extends Activity {
	private MediaPlayer player;
	private boolean bTogglePause = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}

	@Override
	protected void onResume() {
		super.onResume();
		player = MediaPlayer.create(this, R.raw.ralph);
	}

	@Override
	protected void onPause() {
		if ( player != null ) {
			player.stop();
			player.release();
			player = null;
		}
		super.onPause();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		int curPos = 0;

		if ( player != null ) {
			switch (keyCode) {
			case KeyEvent.KEYCODE_DPAD_RIGHT:
				player.seekTo(0);
				player.start();
				break;
			case KeyEvent.KEYCODE_DPAD_UP:
				curPos = player.getCurrentPosition();
				if ( curPos  + 10000 < player.getDuration() ) {
					curPos += 10000;
				}
				player.seekTo( curPos );
				break;
			case KeyEvent.KEYCODE_DPAD_DOWN:
				curPos = player.getCurrentPosition() - 10000;
				if ( curPos < 0 ) {
					curPos = 0;
				}
				player.seekTo( curPos );
				break;
			case KeyEvent.KEYCODE_DPAD_CENTER:
				if (bTogglePause) {
					player.pause();					
				} else {
					player.start();										
				}
				bTogglePause = !bTogglePause;
				break;
			default:
				player.pause();
			}			
		}
		return true;
	}

}